let recorder; // 音频录制器
let audioChunks = []; // 存储音频数据块

var videourl = ""
// 全局就在这搞个百度地图初始化
var map = new BMapGL.Map("container");
map.centerAndZoom(new BMapGL.Point(116.404, 39.915), 11);
var local = new BMapGL.LocalSearch(map, {
    renderOptions: { map: map }
});

map.addEventListener('click', function (e) {
    var text = $("#rtsptxt").val();
    // 基于ajax将用户输入的文本信息发送到后台
    $.ajax({
        url: 'https://43.136.99.209/send/transformjingweidu/',
        type: 'GET',
        data: {
            jingdu: e.latlng.lng,
            weidu:e.latlng.lat
        },
        success: function (res) {
            jd = res.jingdu;
            wd = res.weidu;
            console.log("经度: " + jd +" 纬度: " +wd);
            alert('点击的GPS经纬度：' + jd + ', ' + wd);
        }
    })
});

map.enableScrollWheelZoom(true);

// 获取用户媒体流
const getMediaStream = async () => {
    try {
        const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
        recorder = new MediaRecorder(stream);
        recorder.addEventListener("dataavailable", (event) => {
            audioChunks.push(event.data);
        });
    } catch (error) {
        console.log("获取媒体流失败");
    }
}

// 开始录音
document.getElementById("recordBtn").addEventListener("click", async () => {
    audioChunks = []; // 清空音频数据块
    await getMediaStream();
    recorder.start();
});

// 停止录音
document.getElementById("stopBtn").addEventListener("click", () => {
    recorder.stop();
    console.log("录音结束");
});

// 上传录音
document.getElementById("uploadBtn").addEventListener("click", () => {
    const blob = new Blob(audioChunks, { type: "audio/ogg; codecs=opus" });
    const xhr = new XMLHttpRequest();
    xhr.onload = () => {
        if (xhr.status === 200) {
            console.log("上传音频文件成功");
        } else {
            console.error("上传失败，错误码：" + xhr.status);
        }
    }
    xhr.open("POST", "https://www.likesporting.cn/audio/", true);
    xhr.send(blob);
});

function audio_search() {
    console.log("查询语音识别结果")
    var xhr = new XMLHttpRequest();
    xhr.open('GET', 'https://www.likesporting.cn/audio_result/', true);
    xhr.onload = function () {
        if (xhr.status === 200) {
            console.log(xhr.responseText);
            var response = JSON.parse(xhr.responseText);
            var str = response.result;
            console.log("语音识别结果: " + str);
            alert("语音识别结果: " + str);

        } else if (xhr.status === 500) {
            alert("正在识别，请稍等会再次发起查询");
        } else {
            console.log('请求失败。状态码：' + xhr.status);
        }
    }
    xhr.send();
}

var num = 0;
function paizhao() {
    setInterval(function () {
        num++;
        var xhr = new XMLHttpRequest();
        xhr.open('GET', 'https://www.likesporting.cn/paizhao/', true);
        xhr.onload = function () {
            if (xhr.status === 200) {
                console.log("paizhao success");
                var str = "/static/images/duqian" + num + ".jpg";
                var tag = document.getElementById('choosevideoimage');
                tag.innerHTML = "";
                var add_tag = "<img src=" + str + " style = \" display: block; height=\"500px\"; width=\"100%\" \" " + " alt=" + "\" \" " + ">";
                tag.insertAdjacentHTML('beforeend', add_tag);
            } else {
                console.log('视频流有问题');
                var str = "/static/images/default1.jpg";
                var tag = document.getElementById('choosevideoimage');
                tag.innerHTML = "";
                var add_tag = "<img src=" + str + " alt=" + "\" \" " + ">";
                tag.insertAdjacentHTML('beforeend', add_tag);
            }
        }
        xhr.onerror = function () {
            console.log('paizhao  fail');
        }
        xhr.send();
    }, 8000);
}

function luxiang() {
    var tag = document.getElementById('choosevideoimage');
    var add_tag = "<video id=\"duvideo\" height=\"500\" width=\"600\" controls=\"controls\"></video>";
    tag.insertAdjacentHTML('beforeend', add_tag);

    if (flvjs.isSupported()) {
        var videoElement = document.getElementById('duvideo');
        var flvPlayer = flvjs.createPlayer({
            type: 'flv',
            url: 'http://43.136.99.209:85/live/test.flv'
        });
        flvPlayer.attachMediaElement(videoElement);
        flvPlayer.load();
        flvPlayer.play();
    }
}


// function sendrtspmessage() {
//     var text = $("#rtsptxt").val();
//     // 基于ajax将用户输入的文本信息发送到后台
//     $.ajax({
//         url: '/send/rtspmsg/',
//         type: 'GET',
//         data: {
//             text: text
//         },
//         success: function (res) {
//             console.log("请求发送成功", res)
//         }
//     })
// }

function sendrtspmessage() {
    var rtspvideostream = $("#rtsptxt").val();
    var tmp = rtspvideostream.split("//");
    videourl = "https://" + tmp[1] + ".flv";
}


// function sendmessage() {
//     var text = $("#txt").val();
//     // 基于ajax将用户输入的文本信息发送到后台
//     $.ajax({
//         url: '/send/msg/',
//         type: 'GET',
//         data: {
//             text: text
//         },
//         success: function (res) {
//             console.log("请求发送成功", res)
//         }
//     })
// }

function sendmessage() {
    var text = $("#txt").val();
    console.log('查找地址' + text);
    local.search(text);
}



if (flvjs.isSupported()) {
    var videoElement = document.getElementById('rtspvideo');
    var flvPlayer = flvjs.createPlayer({
        type: 'flv',
        // url:'http://43.136.99.209:85/live/test.flv'
        url: 'https://43.136.99.209:8443/live/test.flv'
        // url:videourl
        // url:'https://likesporting.cn:8443/live/test.flv'
    });
    flvPlayer.attachMediaElement(videoElement);
    flvPlayer.load();
    flvPlayer.play();
}